/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.translatedbible;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextBox;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Button;
import org.jfxserviceconsumer.consumer.ConsumerImpl;
import org.jfxserviceconsumer.parser.JSONParser;
import javafx.scene.layout.Stack;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import org.translatedbible.model.Languages;
import org.translatedbible.model.BibleResponse;
import org.translatedbible.model.TranslatorResponse;
import javafx.geometry.VPos;
import javafx.geometry.HPos;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import org.translatedbible.BibleBooks;
import javafx.scene.control.ToggleGroup;
import javafx.scene.text.TextAlignment;

def BASE_URL = "http://labs.bible.org/api/?passage=";
var sceneRef: Scene;
var bibleSearcher: ConsumerImpl = ConsumerImpl {
            uri: "{BASE_URL}[book]+[charpter]:[verse]&type=json"
            parser: JSONParser {
                clazz: "org.translatedbible.model.BibleResponse" oneObject: true
            }
        }
var translator: ConsumerImpl = ConsumerImpl {
            parser: JSONParser {
                clazz: "org.translatedbible.model.TranslatorResponse"
                //No root, will analyse all the JSON to fill your object
                oneObject: true;
            }
            uri: "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=[q]&langpair=%7C[lang]"
        }
var blockRect: Rectangle = Rectangle {
            focusTraversable: true; fill: Color.TAN
            width: bind sceneRef.width height: bind sceneRef.height
            opacity: 0.75
        }
var txtBox: Label;
var messageBox: Stack = Stack {
            translateX: 0 translateY: 0
            width: bind sceneRef.width height: bind sceneRef.height
            content: [
                blockRect,
                txtBox = Label {
                            width: bind sceneRef.width - 100;
                            text: bind warning;
                            textFill: Color.MIDNIGHTBLUE;
                            textWrap: true; textAlignment: TextAlignment.CENTER
                            font: Font { size: 32 embolden: true  }
                        }
            ]
        }
var warning: String = "Welcome to BibleFX (beta)!\n Translation by Google Translate\n Bible source by and Bible.org\n Send me some Feedback: @william_antonio" on replace {
    if (warning != "") {
        messageBox.visible = true;
        blockRect.requestFocus();
    }
}
var txtOut: TextBox;
var chbSaved:ChoiceBox;
var chbBook: ChoiceBox;
var chbChapter: ChoiceBox;
var chbVerse: ChoiceBox;
var chbLanguages: ChoiceBox;
var tbTrans: ToggleButton;
var tgOldTestament: ToggleButton;
var imgSee: ImageView = ImageView {
            fitWidth: 30 fitHeight: 30
            translateX: bind txtOut.width - imgSee.fitWidth + txtOut.boundsInParent.minX +  70;
            translateY: bind txtOut.height + txtOut.boundsInParent.minY - imgSee.fitHeight + 5;
            image: Image { url: "{__DIR__}see.png" }
            onMouseClicked: function(e) {
                warning = txtOut.text;
            }
        }

var sizeBox:HBox;
var navigation:HBox;
var stageRef:Stage;
var mainBox:VBox;
stageRef = Stage {
    title: "BibleFX"
    width: 570 height: 500
    scene: sceneRef = Scene {
                fill:Color.BEIGE
                stylesheets: "{__DIR__}style.css"
                content: [
                    ImageView{
                        fitWidth: bind sceneRef.width fitHeight: bind sceneRef.height
                        image:Image{ url: "{__DIR__}biblia.jpg"}
                    }
                    VBox {                        
                        nodeVPos: VPos.CENTER; nodeHPos: HPos.CENTER;
                        vpos: VPos.CENTER; hpos: HPos.CENTER
                        translateY: 10 translateX: 80
                        spacing: 30 disable: bind messageBox.visible;
                        content: [
                            HBox {
                                vpos: VPos.CENTER; hpos: HPos.CENTER
                                var tgGroupTestaments: ToggleGroup = ToggleGroup {}
                                spacing: 30
                                content: [
                                    tgOldTestament = ToggleButton { text: "Old Testament" selected: true toggleGroup: tgGroupTestaments }
                                    ToggleButton { text: "New Testament" toggleGroup: tgGroupTestaments }
                                ]
                            }
                            HBox {
                                spacing: 5 vpos: VPos.CENTER; hpos: HPos.CENTER
                                content: [
                                    chbBook = ChoiceBox {
                                                items: bind if (tgOldTestament.selected)
                                                    for (book in BibleBooks.oldTestamentBooks) book.name else
                                                    for (book in BibleBooks.newTestamentBooks) book.name}
                                    chbChapter = ChoiceBox {                                                
                                                items: bind if (tgOldTestament.selected)
                                                    for (i in [1..BibleBooks.oldTestamentBooks[chbBook.selectedIndex].chapter])
                                                        String.valueOf(i) else
                                                    for (i in [1..BibleBooks.newTestamentBooks[chbBook.selectedIndex].chapter])
                                                        String.valueOf(i)
                                            }
                                    Label { text: ":" }
                                    chbVerse = ChoiceBox {
                                                items: bind if (tgOldTestament.selected)
                                                    for (i in [1..BibleBooks.oldTestamentBooks[chbBook.selectedIndex].verses[chbChapter.selectedIndex]])
                                                        String.valueOf(i) else
                                                    for (i in [1..BibleBooks.newTestamentBooks[chbBook.selectedIndex].verses[chbChapter.selectedIndex]])
                                                        String.valueOf(i)
                                            }
                                ]
                            }
                            HBox {
                                spacing: 5
                                vpos: VPos.CENTER; hpos: HPos.CENTER
                                content: [
                                    tbTrans = ToggleButton { text: "Translate" }
                                    chbLanguages = ChoiceBox { items: Languages.LANGUAGES disable: bind not tbTrans.selected }
                                    Button { text: "Translate Now!" action: translate; disable: bind not tbTrans.selected }
                                ]
                            }
                            Button {
                                text: " Search"
                                action: performSearch;
                            }
                            txtOut = TextBox { multiline: true editable: false }
                        ]
                    }
                    imgSee, messageBox,
                    navigation = HBox {
                        hpos: HPos.CENTER spacing: 10
                        translateX: bind (sceneRef.width / 2)  -  navigation.width / 2
                        translateY: bind sceneRef.height - navigation.height - 10                        
                        content: [
                            Button { text: "<<" action: previous }
                            Button {
                                visible: bind messageBox.visible text: "X" action: function() {
                                    messageBox.visible = false;
                                    if (warning != "") warning = "";
                                } }
                            Button { text: ">>" action: next }
                        ]
                    }                  
                ]
            }
}

function performSearch(): Void {    
    if(chbLanguages.selectedItem.toString().trim() == "")   chbLanguages.select(0);
    if(chbChapter.toString().trim() == "")   chbChapter.select(0);
    if(chbVerse.toString().trim() == "")   chbVerse.select(0);
    try{
        bibleSearcher.request([chbBook.selectedItem, chbChapter.selectedItem, chbVerse.selectedItem], function(obj: Object[]): Void {
            var bibleResponse: BibleResponse = obj[0] as BibleResponse;
            txtOut.text = bibleResponse.text;
            warning = "{bibleResponse.bookname} {bibleResponse.chapter}:{bibleResponse.verse} \n {bibleResponse.text}";
            if (tbTrans.selected) {
                translate();
            }
        });
    }catch(e){
        warning = "Please, select Book, Chapter and Verse";
    }
}


function translate() {
    warning = "Translating";
    translator.request([txtOut.text, chbLanguages.selectedItem.toString().split("-")[0].trim()], function(translated: Object[]): Void {
        var tResponse: TranslatorResponse = (translated[0] as TranslatorResponse);
        txtOut.text = tResponse.translatedText.replaceAll("&quot;", "\"");
        warning = "{chbBook.selectedItem} {chbChapter.selectedItem}:{chbVerse.selectedItem} \n""Translated from {tResponse.detectedSourceLanguage} to {chbLanguages.selectedItem}: \n {txtOut.text}";
    });
}

var indexVerse: Integer;
var indexChapter: Integer;
var indexBook: Integer;

function next() {
    setNext(); performSearch();
}

function previous() {
    setPrevious(); performSearch();
}
function setNext() {
    indexVerse = chbVerse.selectedIndex + 1;
    indexChapter = chbChapter.selectedIndex;
    indexBook = chbBook.selectedIndex;

    if (indexVerse >= sizeof chbVerse.items) {
        indexChapter++;
        if (indexChapter >= sizeof chbChapter.items) {
            indexBook++;
            if (indexBook >= sizeof chbBook.items) {
                chbBook.select(0);
            } else {
                chbBook.select(indexBook);
            }
            chbChapter.select(0);
            chbVerse.select(0);            
        } else {
            chbChapter.select(indexChapter);            
            chbVerse.select(0);
            
        }
    } else {
        chbVerse.select(indexVerse);       
    }

}

/*TODO*/
function setPrevious() {
    indexVerse = chbVerse.selectedIndex - 1;
    indexChapter = chbChapter.selectedIndex;
    indexBook = chbBook.selectedIndex;

    if (indexVerse < 0) {
        indexChapter--;
        if (indexChapter < 0) {
            indexBook--;
            if (indexBook < 0) {
                chbBook.select(sizeof chbBook.items - 1);
            } else {
                chbBook.select(indexBook);
            }
            chbChapter.select(sizeof chbChapter.items - 1);
            chbVerse.select(sizeof chbVerse.items - 1);
        } else {
            chbChapter.select(indexChapter);
            chbVerse.select(sizeof chbVerse.items - 1);
        }
    } else {
        chbVerse.select(indexVerse);        
    }
}
